/*
Copyright (c) 2013 Mihail Volkov

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef APPLICATION_H
#define APPLICATION_H

#include <QApplication>
#include <QSettings>
#include <QMap>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTextBrowser>
#include <QFile>
#include <QTimer>
#include <QPointer>

#include "statemach.h"
#include "connection.h"
// GUI
#include <QFileDialog>
#include <QProgressDialog>
#include "mainwindow.h"
#include "connectdialog.h"
#include "aboutdialog.h"
// other
#include "unit.h"

// access manager to intercept htmd:/filepath and ass:/filepath schemes
class HtMdNetworkAccessManager: public QNetworkAccessManager
{
	Q_OBJECT

public:
	HtMdNetworkAccessManager(QNetworkAccessManager *oldManager, QObject *parent = 0);

protected:
	QNetworkReply *createRequest(Operation operation, const QNetworkRequest &request, QIODevice *device);
};

class HtMdLocalFileReply : public QNetworkReply
{
	Q_OBJECT
	QFile mFile;
	QTimer mAsyncReadyNotifier;
	bool mOpenOk;

public:
	HtMdLocalFileReply(const QString &filename);
	void abort();
	qint64 bytesAvailable() const;
	bool isSequential() const;

protected:
	qint64 readData(char *data, qint64 maxSize);

private slots:
	void doNotifyReady (); // that a file is (not) opened
};

// the main application class
class HtMdConsoleApp: public QApplication
{
	friend class Unit;

	Q_OBJECT

	static HtMdConsoleApp *spInstance;

	MainWindow *mpMainWindow;
	ConnectDialog *mpConnectDialog;
	AboutDialog *mpAboutDialog;
	QFileDialog *mpFileDialog;
	QProgressDialog *mpFileProgressDialog;
	HtMdConnection *mpConnection;
	QSettings mSettings;

	void saveSettings ();
	void restoreSettings ();

	typedef QMap<unsigned,QPointer<Unit> > Units;
	Units mUnits;
	void closeAllUnits ();

	void createFileDialog ();
	void disposeFileDialog ();

public: // global vars

	// machine
	SMMachine appMachine;

	SMState
		stateBegin,
		stateShutdown,
		stateEnd,
		stateDisconnected,
		stateConnectDialog,
		stateConnecting,
		stateConnectFailed,
		stateDisconnecting,
		stateConnected;

	SMEvent
		evtAppStarted,
		evtConnectDialogOpen,
		evtConnectDialogOk,
		evtConnectDialogCancel,
		evtConnectionEstablished,
		evtConnectionFailed,
		evtConnectionServerDropped,
		evtConnectionClientDropped,
		evtCmdDisconnect,
		evtCmdExit;

	// connect parameters
	QString connectParameters;
	QString kitLocation;
	QString assetsLocation;
	bool locationsChanged;

	SMMachine fileDialogMachine;

	SMState
		stateFdmNone,
		stateFdmDownload,
		stateFdmDownloadInProgress,
		stateFdmUpload,
		stateFdmUploadInProgress,
		stateFdmCancelled;

	SMEvent
		evtFdmDownloadRequest,
		evtFdmUploadRequest,
		evtFdmConfirm,
		evtFdmCancel,
		evtFdmCompleted;
		// ^dialog, or the process, or app cancel, or disconnect

	QString fileSuggestedFilter,
		fileSuggestedName,
		fileSelectedName;
	QDir lastFileDir;
	enum FileMode
	{
		FM_NONE,
		FM_UPLOAD,
		FM_DOWNLOAD
	} fileMode;

public: // methods
	HtMdConsoleApp (int &,char **);
	~HtMdConsoleApp ();
	static HtMdConsoleApp *instance ()
	{ return spInstance; }

	Unit *getUnit (unsigned unitId);
	Unit *getOrCreateUnit (unsigned unitId);
	void closeUnit (unsigned unitId);

	void setFileProgress (int bytesSofar,int bytesMax);
	void setStatusText (const QString &);

	QString decodeSchemePath (const QString &);
	bool isConnected ();

	QTextBrowser *getJSErrorConsole ();
	QAction *getGlobalAction (const QString &actionName);

signals:
	void fileConfirmed (QString fileName,bool uploading);
	void fileCancelled ();

private slots:
	void onEnterStateBegin (SMMachine *);
	void onEnterStateShutdown (SMMachine *);
	void onEnterStateEnd (SMMachine *);
	void onEnterStateDisconnected (SMMachine *);
	void onEnterStateConnectDialog (SMMachine *);
	void onEnterStateConnecting (SMMachine *);
	void onEnterStateConnectFailed (SMMachine *);
	void onEnterStateDisconnecting (SMMachine *);
	void onEnterStateConnected (SMMachine *);

	void onEnterStateFdmNone (SMMachine *);
	void onEnterStateFdmDownload (SMMachine *);
	void onEnterStateFdmDownloadInProgress (SMMachine *);
	void onEnterStateFdmUpload (SMMachine *);
	void onEnterStateFdmUploadInProgress (SMMachine *);
	void onEnterStateFdmCancelled (SMMachine *);

	void showAbout ();
	void showDocRu ();
	void showDocEn ();
};

#define APP (*HtMdConsoleApp::instance ())

#endif // APPLICATION_H
